package service

import (
	"barrage-go/consts"
	"barrage-go/models"
	"barrage-go/proto/pb"
	"barrage-go/utils"
	"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"time"
)

func WebClientHeartBeatReq(msg []byte, ws *websocket.Conn) {

	heartBeatReq := pb.WebClientHeartBeatReq{}
	err := proto.Unmarshal(msg, &heartBeatReq)
	if err != nil {
		log.Println("解析心跳求信息发生异常:", err)
	}

	videoId := heartBeatReq.VideoId
	heartBeatResp := pb.WebClientHeartBeatResp{}
	heartBeatResp.BarrageTotalWatchCount = GetBarrageTotalWatchCount(videoId)
	heartBeatResp.BarrageOnlineCount = GetBarrageOnlineCount(videoId)
	heartBeatResp.BarrageTotalCount = models.GetBarrageTotalCount(videoId)

	heartbeatBytes, _ := proto.Marshal(&heartBeatResp)
	clientResp := pb.Barrage{
		MsgType:   consts.WebClientHeartBeatResp,
		BytesData: heartbeatBytes,
	}

	client, _ := proto.Marshal(&clientResp)
	err = ws.WriteMessage(websocket.BinaryMessage, client)
	if err != nil {
		log.Println("返回给客户端历史弹幕消息发生异常:", err)
	}
}

func GetBarrageTotalWatchCount(videoId string) int32 {
	parseInt, _ := strconv.ParseInt(utils.Get(consts.BarrageTotalWatch+videoId), 10, 32)
	return int32(parseInt)
}

func GetBarrageOnlineCount(videoId string) int32 {
	parseInt, _ := strconv.ParseInt(utils.Get(consts.BarrageOnlinePopulation+videoId), 10, 32)
	return int32(parseInt)
}

func Ping(ws *websocket.Conn) {
	heartbeatTicker := time.NewTicker(time.Second)
	defer heartbeatTicker.Stop()
	for {
		select {
		case <-heartbeatTicker.C:
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				log.Println("心跳包发送失败:", err)
			}
		default:
			log.Println("心跳包未知信息")
		}
	}
}
